<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Process;

use App\Service\BinanceService;
use App\Strategy\MaCrossoverStrategy;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Process\AbstractProcess;
use Hyperf\Process\Annotation\Process;
use Swoole\Timer;
use Swoole\Coroutine;

/**
 * @Process(name="strategy_runner", enableCoroutine=true, nums=1)
 */
class StrategyRunner extends AbstractProcess
{
    /**
     * @Inject
     */
    protected BinanceService $binance;

    /**
     *@Inject()
     */
    protected MaCrossoverStrategy $strategy;

    private bool $holding = false;
    public function handle(): void
    {
        file_put_contents(BASE_PATH . '/runtime/strategy_log.txt', 'Process started at ' . date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);

        Timer::tick(5000, function () {
            file_put_contents(BASE_PATH . '/runtime/tick_log.txt', 'Tick at ' . date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);
        });

        // 阻塞进程防止退出
        while (true) {
            Coroutine::sleep(60); // 每分钟挂一次
        }
    }

    public function handle111(): void
    {
        file_put_contents(BASE_PATH . '/runtime/strategy_log.txt', 'Process started at ' . date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND);

        $symbol = 'BTCUSDT';

        // 每 5 秒执行一次策略
        Timer::tick(10000, function () {
            var_dump(123);
            //            go(function () use ($symbol) {
            //                return 1;
            //                try {
            //                    $result = $this->strategy->handle($symbol);
            //                    if ($result['action'] === 'buy') {
            //                        $this->holding = true;
            //                        $this->binance->placeOrderByUsdt($symbol, 'BUY', 30, 30);
            //                        echo "Buy triggered at {$result['price']}\n";
            //                    } elseif ($result['action'] === 'sell') {
            //                        $this->binance->placeOrderByUsdt($symbol, 'SELL', 30, 30);
            //                        echo "Sell triggered at {$result['price']}\n";
            //                    } else {
            //                        echo 'No action at ' . date('H:i:s') . "\n";
            //                    }
            //                } catch (\Throwable $e) {
            //                    var_dump($e->getMessage());
            //                }
            //            });
        });
    }
}
